#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"
LTNode* BuyLisTNode(LTDataType x)
{
	LTNode* phead = (LTNode*)malloc(sizeof(LTNode));
	if (phead == NULL)
	{
		perror("BuyLisTNode::malloc");
		return NULL;
	}
	phead->next = NULL;
	phead->prev = NULL;
	phead->data = x;
	return phead;
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	printf("<head>");

	while (cur != phead)
	{
		printf("<=>%d", cur->data);		
		cur = cur->next;
	}
	printf("\n");
}

LTNode* LTInit()
{
	//assert(phead);
	LTNode*phead=BuyLisTNode(1);

	phead->prev = phead;
	phead->next = phead;

	return phead;

}

void LTDestroy(LTNode*phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		LTNode* next = cur->next;
		free(cur);
		cur = next;
	}
	/*phead->next = phead;
	phead->prev = phead;*/
	free(phead);

}


void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newhead = BuyLisTNode(x);
	LTNode* tail = phead->prev;
	newhead->prev = tail;
	tail->next = newhead;
	phead->prev = newhead;
	newhead->next = phead;

}
void LTPopBack(LTNode* phead)
{
	assert(phead);
	LTNode* del = phead->prev;
	LTNode* tail = del->prev;
	phead->prev = tail;
	tail->next = phead;
	if (del != phead)
	{
		free(del);
		del = NULL;
	}

}

void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = BuyLisTNode(x);
	LTNode* tail = phead->next;
	newnode->prev = phead;
	phead->next = newnode;
	newnode->next = tail;
	tail->prev = newnode;

}
void LTPopFront(LTNode* phead)
{
	assert(phead);
	LTNode* cur = phead->next;
	if(cur != phead)
	{
		LTNode* next = cur->next;
		next->prev = phead;
		phead->next = next;
		free(cur);
		cur = next;
	}

}


LTNode* ListFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data != x)
		{
			cur = cur->next;
		}
		else
			return cur;

	}

	return NULL;

}

void ListInsert(LTNode* pos, LTDataType x)
{

	assert(pos);
	LTNode* prev = pos->prev;
	LTNode*newnode=BuyLisTNode(x);
	newnode->next = pos;
	pos->prev = newnode;
	prev->next = newnode;
	newnode->prev = prev;

}

void ListErase(LTNode* pos)
{
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);

}